package com.example.ai.uploadImage;

import com.jcraft.jsch.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class UploadImage {
    private static final String SERVER = "10.2.188.107";
    private static final int PORT = 22;
    private static final String USERNAME = "root";
    private static final String PASSWORD = "zjzhjs-2023";

    public static void main(String[] args) {
        String localDirPath = "E:\\study\\data\\result\\val";
        String remoteBaseDir = "/root/yolo-project/data/val";
//        String localDirPath = "E:\\study\\test";
//        String remoteBaseDir = "/root/yolo-project";

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(USERNAME, SERVER, PORT);
            session.setPassword(PASSWORD);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setConfig("PreferredAuthentications", "password");
            session.connect(5000); // 添加超时设置

            Channel channel = session.openChannel("sftp");
            channel.connect(5000);
            ChannelSftp sftp = (ChannelSftp) channel;

            // 检查根目录权限
            testRootPermissions(sftp);

            uploadDirectory(sftp, new File(localDirPath), remoteBaseDir);

            sftp.exit();
            channel.disconnect();
            session.disconnect();
            System.out.println("文件夹上传完成");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void testRootPermissions(ChannelSftp sftp) throws SftpException {
        try {
            sftp.cd("/");
            System.out.println("[权限检查] 根目录访问正常");

            // 创建测试目录
            String testDir = "/sftp-perm-test-" + System.currentTimeMillis();
            sftp.mkdir(testDir);
            sftp.rmdir(testDir);
            System.out.println("[权限检查] 创建/删除测试目录成功");
        } catch (SftpException e) {
            System.err.println("根目录权限异常! 错误代码: " + e.id);
            throw new RuntimeException("服务器权限不足，请检查: " + e.getMessage(), e);
        }
    }

    private static void uploadDirectory(ChannelSftp sftp, File localDir, String remoteDir)
            throws SftpException, IOException {
        // 标准化路径
        remoteDir = remoteDir.replace("\\", "/");
        createDirectoryIfNotExists(sftp, remoteDir);

        File[] files = localDir.listFiles();
        if (files == null) return;

        for (File file : files) {
            String remotePath = remoteDir + "/" + file.getName();
            if (file.isDirectory()) {
                uploadDirectory(sftp, file, remotePath);
            } else {
                uploadFile(sftp, file.getAbsolutePath(), remoteDir);
                System.out.println("已上传: " + file);
            }
        }
    }

    private static void createDirectoryIfNotExists(ChannelSftp sftp, String dirPath) throws SftpException {
        dirPath = dirPath.replace("\\", "/"); // 确保Linux路径格式

        try {
            SftpATTRS attrs = sftp.lstat(dirPath);
            if (attrs.isDir()) {
                return; // 目录已存在
            }
            throw new SftpException(ChannelSftp.SSH_FX_FAILURE, "路径已存在但不是目录: " + dirPath);
        } catch (SftpException e) {
            if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
                // 递归创建父目录
                int lastSlash = dirPath.lastIndexOf('/');
                if (lastSlash > 0) {
                    String parent = dirPath.substring(0, lastSlash);
                    createDirectoryIfNotExists(sftp, parent);
                }

                // 创建当前目录
                try {
                    sftp.mkdir(dirPath);
                    System.out.println("创建目录成功: " + dirPath);
                } catch (SftpException mkdirEx) {
                    // 处理目录创建冲突
                    if (mkdirEx.id != ChannelSftp.SSH_FX_FAILURE) throw mkdirEx;

                    try {
                        if (sftp.lstat(dirPath).isDir()) {
                            System.out.println("目录已被其他进程创建: " + dirPath);
                            return;
                        }
                    } catch (SftpException ex) {
                        System.err.println("目录创建失败: " + dirPath);
                        System.err.println("最终错误: " + ex);
                    }
                    throw new SftpException(ChannelSftp.SSH_FX_PERMISSION_DENIED,
                            "目录创建被拒绝，请检查权限: " + dirPath);
                }
            } else {
                throw e;
            }
        }
    }

    private static void uploadFile(ChannelSftp sftp, String localFile, String remoteDir)
            throws SftpException, IOException {
        File file = new File(localFile);
        String remotePath = remoteDir.replace("\\", "/") + "/" + file.getName();

        try (InputStream is = new FileInputStream(file)) {
            sftp.put(is, remotePath);
        } catch (SftpException e) {
            System.err.println("文件上传失败: " + remotePath);
            throw e;
        }
    }
}
